package winFrom

import (
	"fmt"
	"log"
	"sort"
	"strconv"
	//"time"
)

import (
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

//var isSpecialMode = walk.NewMutableCondition()

type Numurl struct {
	Id  int
	Num string
}

func Rtnumurl() []*Numurl {
	return []*Numurl{
		{1, "2"}, {2, "3"}, {3, "4"}, {4, "5"}, {5, "6"}, {6, "7"}}
}

type Urlmodel struct {
	Num1 string
	walk.TableModelBase
	walk.SorterBase
	evenBitmap *walk.Bitmap
	oddIcon    *walk.Icon
	sortColumn int
	sortOrder  walk.SortOrder
	sqlhelp
}

func NewUrlModel() *Urlmodel {
	m := new(Urlmodel)
	m.ResetRows()
	return m
}
func (m *Urlmodel) RowCount() int {
	return len(m.Tb_urls)
}
func (m *Urlmodel) Value(row, col int) interface{} {
	item := m.Tb_urls[row]

	switch col {
	case 0:
		//fmt.Println(strconv.FormatInt(int64(item.urlid), 10))
		return item.urlid

	case 1:
		//fmt.Println(item.url)
		return item.url

	case 2:
		if item.isDownload == -1 {
			return "正在队列"
		}
		if item.isDownload == 0 {
			return "等待开始"
		}
		if item.isDownload == 1 {
			return "正在开始"
		}
		if item.isDownload == 2 {
			return "已经完成"
		}
		return "无状态"

	case 3:
		return item.startTime
	case 4:
		return item.endTime
	}

	panic("unexpected col")
}
func (m *Urlmodel) ResetRows() {

	m.Ini_Tb_url_Clear(`select urlid,url,isDownload,startTime,endTime from Tb_url `)
	m.PublishRowsReset()

	m.Sort(m.sortColumn, m.sortOrder)
}
func (m *Urlmodel) Sort(col int, order walk.SortOrder) error {
	m.sortColumn, m.sortOrder = col, order

	sort.Sort(m)

	return m.SorterBase.Sort(col, order)
}
func (m *Urlmodel) Len() int {
	return len(m.Tb_urls)
}
func (m *Urlmodel) Less(i, j int) bool {
	a, b := m.Tb_urls[i], m.Tb_urls[j]

	c := func(ls bool) bool {
		if m.sortOrder == walk.SortAscending {
			return ls
		}

		return !ls
	}
	switch m.sortColumn {
	case 0:
		return c(a.urlid < b.urlid)
	case 1:
		return c(a.url < b.url)

	case 2:
		return c(a.isDownload < b.isDownload)

	case 3:
		return c(a.startTime < b.startTime)
	case 4:
		return c(a.endTime < b.endTime)
	}

	panic("unreachable")
}

func (m *Urlmodel) Swap(i, j int) {
	m.Tb_urls[i], m.Tb_urls[j] = m.Tb_urls[j], m.Tb_urls[i]
}

func Formshow(mw *MyMainWindow) {
	//MustRegisterCondition("isSpecialMode", isSpecialMode)

	mw.ButtonInt = true
	var openAction *walk.Action
	var db *walk.DataBinder
	var ep walk.ErrorPresenter
	//var urldata *Urlmodel
	var toggleSpecialModePB *walk.PushButton
	mw.Urlmodel = NewUrlModel()
	model := mw.Urlmodel
	mw.Urlmodel.Num1 = strconv.Itoa(mw.Urlmodel.RetUrlDownlodingCount())

	//mw.Urlmodel.Ini_Tb_url(`select top ` + mw.Urlmodel.Num1 + `  urlid,url,isDownload,startTime,endTime
	//	from Tb_url where isDownload='0' `)
	////var one sync.Once
	////one.Do( )

	//chnnmw := make(chan *MyMainWindow)

	//go startDownChann(chnnmw)
	//chnnmw <- mw

	if err := (MainWindow{
		AssignTo: &mw.MainWindow,
		Title:    "启明星辰补丁下载",
		MinSize:  Size{800, 600},
		Layout:   VBox{},

		DataBinder: DataBinder{
			AssignTo:       &db,
			DataSource:     model,
			ErrorPresenter: ErrorPresenterRef{&ep},
		},
		MenuItems: []MenuItem{
			Menu{
				Text: "文件",

				Items: []MenuItem{
					Action{
						AssignTo: &openAction,
						Text:     "新建",
						Image:    "./img/open.png",

						Shortcut:    Shortcut{walk.ModControl, walk.KeyO},
						OnTriggered: mw.openAction_Triggered,
					},

					Separator{},
					Action{
						Text:        "关闭",
						OnTriggered: func() { mw.Close() },
					},
				},
			},
			Menu{
				Text: "帮助",
				Items: []MenuItem{
					Action{
						//AssignTo:    &showAboutBoxAction,
						Text:        "关于",
						OnTriggered: mw.showAboutBoxAction_Triggered,
					},
				},
			},
		},

		Children: []Widget{
			Composite{
				Layout: Grid{},
				Children: []Widget{

					Label{
						Row:    0,
						Column: 0,
						Text:   "同时下载任务个数:",
					},
					ComboBox{
						Row:    0,
						Column: 3,
						Value:  Bind("Num1"),

						Model: []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"},
					},
					Label{
						Row:    0,
						Column: 1,
						Text:   "",
					},
					PushButton{
						AssignTo:   &toggleSpecialModePB,
						Text:       "刷新",
						Row:        0,
						Column:     4,
						ColumnSpan: 1,
						OnClicked: func() {
							mw.ResetRows()
						},
					},
					Label{
						Row:    0,
						Column: 2,
						Text:   "",
					},

					PushButton{
						AssignTo:   &toggleSpecialModePB,
						Text:       "开始执行",
						Row:        3,
						Column:     4,
						ColumnSpan: 1,
						OnClicked: func() {
							mw.Urlmodel.ExecUrlListSql("update UrlCount set url_count='" + mw.Urlmodel.Num1 + "'")
							//toggleSpecialModePB.SetText("执行中")
							if err := db.Submit(); err != nil {

								fmt.Println("db.Submit()", err)
								return
							}
							if !mw.ButtonInt {
								//
							}
							RunDialogOKInfoDownload(mw)
						},
					},
					PushButton{
						AssignTo:   &toggleSpecialModePB,
						Text:       "结束执行",
						Row:        3,
						Column:     3,
						ColumnSpan: 1,
						OnClicked: func() {
							RunDialogOKCancel_URL_InfoDownload(mw)

						},
					},
					TableView{
						AlternatingRowBGColor: walk.RGB(255, 255, 224),
						CheckBoxes:            true,
						ColumnsOrderable:      true,
						Row:                   1,
						Column:                0,
						ColumnSpan:            5,
						Columns: []TableViewColumn{
							{Title: "ID"},
							{Title: "URL地址", Width: 380},
							{Title: "下载状态"},
							{Title: "开始时间", Width: 90},
							{Title: "结束时间", Width: 90},
						},

						Model: model,
					},
				},
			},
		},
	}.Create()); err != nil {
		log.Fatal(err)
	}
	//go func() {
	//	for {
	//		time.Sleep(3 * time.Second)

	//		mw.ResetRows()

	//	}
	//}()
	//#####################打算添加walk的关闭事件#################################
	//var canceled bool
	////	((walk.MainWindow)(*(mw.MainWindow)))

	//walk.MainWindow.CloseEvent.Attach(func(canceled *bool, reason walk.CloseReason) {
	//	fmt.Println("adfasdfsf")
	//}(canceled, walk.CloseReasonUnknown))
	mw.Run()

}

type MyMainWindow struct {
	*walk.MainWindow
	*Urlmodel
	ButtonInt bool //开始或者停止下载
	OnCloseed walk.EventHandler
}

func (mw *MyMainWindow) openAction_Triggered() {
	if cmd, err := RunAddUrlDialog(mw); err != nil {
		log.Print(err)

	} else if cmd == walk.DlgCmdOK {
		//outTE.SetText(fmt.Sprintf("%+v", animal))
	}
}

func (mw *MyMainWindow) newAction_Triggered() {
	walk.MsgBox(mw, "New", "Newing something up... or not.", walk.MsgBoxIconInformation)
}

func (mw *MyMainWindow) changeViewAction_Triggered() {
	walk.MsgBox(mw, "Change View", "By now you may have guessed it. Nothing changed.", walk.MsgBoxIconInformation)
}

func (mw *MyMainWindow) showAboutBoxAction_Triggered() {

}

func (mw *MyMainWindow) specialAction_Triggered() {
	walk.MsgBox(mw, "Special", "Nothing to see here.", walk.MsgBoxIconInformation)
}
